package com.jmx.tomcat.worker;

import com.jmx.tomcat.dispatcher.Server;
import com.jmx.tomcat.http.HttpRequest;
import com.jmx.tomcat.http.HttpResponse;
import com.jmx.tomcat.servlet.api.Servlet;

import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

/**
 * 负责处理一次 http 请求，一个线程处理一次请求
 * @author: jmx
 * @date: 2023-08-11 17:36
 * @version: 1.0
 */
public class RequestHandlerThread implements Runnable{
    private Socket socket;

    public RequestHandlerThread(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    private static final Logger logger = Logger.getLogger(RequestHandlerThread.class.getName());

    @Override
    public void run() {
        try {
            //从网络IO中解析HTTP协议内容，构建请求、响应对象中
            HttpRequest httpRequest = new HttpRequest(socket.getInputStream());
            HttpResponse httpResponse = new HttpResponse(socket.getOutputStream());
            logger.info("ip【"+socket.getInetAddress().getHostAddress()+"】 访问地址"+httpRequest.getPattern());
            //根据请求地址映射到对应的Servlet进行处理
            String pattern = httpRequest.getPattern();
            String s = Server.patternMap.get(pattern);
            Servlet servlet = getServlet(s);
            if(servlet!=null){
                servlet.service(httpRequest,httpResponse);
            }else{
                //如果没有找到对应的Servlet则检查访问的是否是静态资源
                String replace = pattern.replace("/", "");
                String staticPath = findStaticPath(replace);
                if(staticPath !=null &&!staticPath.isEmpty()) {
                    FileInputStream fileInputStream = new FileInputStream(staticPath);
                    byte[] buffer = new byte[1024];
                    int readLen = 0;
                    OutputStream outputStream = httpResponse.getOutputStream();
                    while ((readLen=fileInputStream.read(buffer))!=-1){
                        outputStream.write(buffer,0,readLen);
                    }
                    outputStream.flush();
                }else {
                    //访问的路径不存在
                    OutputStream outputStream = httpResponse.getOutputStream();
                    outputStream.write("<h1>404 not found</h1>".getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    private Servlet getServlet(String className){
        Servlet servlet = null;
        if(className!=null&&(servlet=Server.servletMap.get(className))!=null){
            return servlet;
        }
        return null;
    }
    private String findStaticPath(String p){
        // 获取当前类的ClassLoader
        ClassLoader classLoader = Server.class.getClassLoader();
        // 获取资源的URL
        URL resourceURL = classLoader.getResource(p);
        if(resourceURL!=null){
            return resourceURL.getPath();
        }
        return null;
    }
}
